﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.OleDb;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Net;
using Newtonsoft;
using SimpleApp.Models;
using System.Xml;
using System.IO;


namespace SimpleApp.Controllers
{
    public class EVEController : Controller
    {
        //
        // GET: /EVE/

        public ActionResult Index()
        {
            string pathSave = Server.MapPath("~/Content/UploadedFolder/eve.json").ToString();
            if(System.IO.File.Exists(pathSave))
            {
                ViewBag.hasFile =  true;
            }
            else 
            {
                ViewBag.hasFile = null;
            }
            return View();
        }

        [HttpPost]
        public ActionResult Transfer()
        {
            string result = "";
            if (Request.Files["uploadfile"].ContentLength > 0)
            {
                string extension = System.IO.Path.GetExtension(Request.Files["uploadfile"].FileName);
                string pathSave = string.Format("{0}/{1}", Server.MapPath("~/Content/UploadedFolder"), Request.Files["uploadfile"].FileName);
                Request.Files["uploadfile"].SaveAs(pathSave);
                string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + pathSave + ";Extended Properties=Excel 12.0;Persist Security Info=False";
                OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
                excelConnection.Open();

                DataTable dt = new DataTable();
                dt = excelConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                String[] excelSheets = new String[dt.Rows.Count];
                int t = 0;
                //excel data saves in temp file here.
                foreach (DataRow row in dt.Rows)
                {
                    excelSheets[t] = row["TABLE_NAME"].ToString();
                    t++;
                }
                OleDbConnection excelConnection1 = new OleDbConnection(excelConnectionString);
                DataSet ds = new DataSet();

                for (int i = 0; i < excelSheets.Count(); i++)
                {
                    string query = string.Format("Select * from [{0}]", excelSheets[i]);
                    using (OleDbDataAdapter dataAdapter = new OleDbDataAdapter(query, excelConnection1))
                    {
                        ds = new DataSet();
                        dataAdapter.Fill(ds);
                    }
                    DataTable dtSheet = ds.Tables[0];
                    string strSheet = JsonConvert.SerializeObject(dtSheet, new DataTableConverter());
                    if (i == 0)
                    {
                        result = "\"" + excelSheets[i] + "\":" + strSheet;
                    }
                    else
                    {
                        result = "\"" + excelSheets[i] + "\":" + strSheet + "," + result;
                    }
                }


                result = "{" + result + "}";
                excelConnection.Close();

                using (System.IO.StreamWriter sw = System.IO.File.CreateText(Server.MapPath("~/Content/UploadedFolder/eve.json")))
                {
                    sw.WriteLine(result);
                } 
            }
            return  View("Index");
            
          
        }



        [HttpPost]
        public ActionResult Market(string typeid, string regionid = null, string systemid = null)
        {
            string root = "http://www.ceve-market.org/api/market/";
            string strtype = "type/" + typeid + ".json";
            string[] regionids = null;
            if (regionid != null) {
                regionids = regionid.Split(',');
            }
            string strregion, url;
            List<Market> ms = new List<Market>();
            WebClient wc = new WebClient();

            for (int i = 0; i < regionids.Count(); i++) 
            {
                strregion = regionid != null ? "region/" + regionids[i] +"/" : "";
                url = root + strregion  + strtype;
                byte[] bResponse = wc.DownloadData(url);
                string strResponse = Encoding.ASCII.GetString(bResponse);
                Market m = JsonConvert.DeserializeObject<Market>(strResponse);
                m.area = regionids[i];
                m.thing = typeid;
                ms.Add(m);
            }
               
            return PartialView("Market", ms);
        }

  
        public ActionResult QuickLook(string typeid, string regionlimit)
        {
            string root = "http://www.ceve-market.org/api/quicklook?";
            string strtype = "typeid=" + typeid ;
            string strregion = "&regionlimit=" + regionlimit ;
            string url = root + strtype + strregion;

            WebClient wc = new WebClient();
            byte[] bResponse = wc.DownloadData(url);
            string strResponse = Encoding.UTF8.GetString(bResponse);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(strResponse);

            string jsonText = JsonConvert.SerializeObject(doc.ChildNodes[1].ChildNodes[0]);

            JObject content = JObject.Parse(jsonText);
            //content["quicklook"]["sell_orders"] = content["quicklook"]["sell_orders"]["order"];
            //content["quicklook"]["buy_orders"] = content["quicklook"]["buy_orders"]["order"];
            QuickLook m = JsonConvert.DeserializeObject<QuickLook>(content["quicklook"].ToString());
            List<OrderList> ol = m.buy_orders.order;
            List<OrderList> sl = m.sell_orders.order;
            m.buy_orders.order = ol.OrderByDescending(t => t.price).Take(5).ToList<OrderList>();
            m.sell_orders.order = sl.OrderBy(t => t.price).Take(5).ToList<OrderList>();
            return View(m);
        }
   
    }
}
